package zack.gateway.core.session.defaults;

import zack.gateway.core.datasource.DataSource;
import zack.gateway.core.datasource.unpooled.UnpooledDataSourceFactory;
import zack.gateway.core.executor.Executor;
import zack.gateway.core.session.Configuration;
import zack.gateway.core.session.GatewaySession;
import zack.gateway.core.session.GatewaySessionFactory;

import java.util.concurrent.ExecutionException;

/**网关会话工厂，开启rpc调用会话
 * @author A1793
 */
public class DefaultGatewaySessionFactory implements GatewaySessionFactory {

    private Configuration configuration;


    public DefaultGatewaySessionFactory(Configuration configuration) {

        this.configuration = configuration;
    }

    public Configuration getConfiguration() {
        return configuration;
    }

    /**
     * 建立数据源，提供給session，让他创建连接，进行rpc调用
     * @param uri
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public GatewaySession openSession(String uri) throws ExecutionException, InterruptedException {

        UnpooledDataSourceFactory unpooledDataSourceFactory = new UnpooledDataSourceFactory();
        unpooledDataSourceFactory.setProperties(configuration,uri);
        DataSource dataSource = unpooledDataSourceFactory.getDataSource();
        Executor executor = configuration.newExecutor(dataSource.getConnection());
        return new DefaultGatewaySession(configuration,uri,executor);
    }
}
